package com.suyx.job.service.impl;

import com.suyx.job.dao.EmailRepository;
import com.suyx.job.entity.EmailServerInfo;
import com.suyx.job.entity.Page;
import com.suyx.job.service.IEmailService;
import com.suyx.job.service.base.impl.MyServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/31 0031 10:03
 * @Description:
 */
@Slf4j
@Service
public class EmailServiceImpl extends MyServiceImpl<EmailServerInfo,Integer> implements IEmailService {

    private EmailRepository emailRepository;

    @Autowired
    public EmailServiceImpl(EmailRepository emailRepository) {
        super(emailRepository);
        this.emailRepository = emailRepository;
    }

    @Override
    public List<EmailServerInfo> findGroupEmail(String jobGroupNo) {
        return emailRepository.findByJobGroupNo(jobGroupNo);
    }

    @Override
    public Page findJobEmailPage(EmailServerInfo emailServerInfo, int page, Integer limit) {
        return new Page(
                emailRepository.findAll((Root<EmailServerInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(emailServerInfo.getEmailName())){
                        predicates.add(cb.like(root.get("emailName").as(String.class), "%"+emailServerInfo.getEmailName() + "%"));
                    }
                    if(!StringUtils.isEmpty(emailServerInfo.getJobGroupNo())){
                        predicates.add(cb.equal(root.get("jobGroupNo").as(String.class), emailServerInfo.getEmailName()));
                    }
                    return  query.where(predicates.toArray(new Predicate[0])).getRestriction();
                }, PageRequest.of(page,limit)));
    }
}
